<template>
  <div class="components-container">
    <VueSplitter class="flowChartWrap" :min-percent="5" :initial-percent="17">
      <template #left-pane>
        <ComponentTree style="width: auto" />
      </template>
      <template #right-pane>
        <VueSplitter class="flowChartWrap" :initial-percent="node_outerSplitPaneSize">
          <!-- 画布 -->
          <template #left-pane>
            <ElMain>
              <ElContainer>
                <!-- 2.2 画布内容 -->
                <ElContainer>
                  <!-- 2.2.1 flow面板 -->
                  <ElMain class="main">
                    <div class="mainContainer" @drop="dropHandle" @dragover="dragoverHandle">
                      <div>
                        <ElButton
                          style="margin-top: 10px; margin-left: 10px"
                          icon="VideoPlay"
                          :disabled="isExecDisable"
                          size="small"
                          @click="execModel"
                          >执行</ElButton
                        >
                        <ElButton
                          style="margin-top: 10px; margin-right: 10px; float: right"
                          icon="VideoPlay"
                          size="small"
                          @click="saveData"
                          >保存</ElButton
                        >
                      </div>
                      <div id="mainContainer" />
                    </div>
                  </ElMain>
                </ElContainer>
              </ElContainer>
            </ElMain>
          </template>
          <template #right-pane>
            <VueSplitter
              v-if="isShowNode"
              :initial-percent="tab_outerSplitPaneSize"
              class="flowChartWrap"
              is-horizontal
            >
              <!-- 参数 -->
              <template #top-pane>
                <ElAside width="100%" style="height: 100%" class="right">
                  <ElContainer id="mainNodeInfo" style="height: 100%">
                    <ElMain>
                      <div class="title">参数配置-{{ currentNodeType }}</div>
                      <!-- <ElDivider>
                        <span style="font-weight: bolder">{{ '参数配置-' + currentNodeType }}</span>
                      </ElDivider> -->
                      <div class="model-attr">
                        <!-- 隐私保护算法 -->
                        <!-- <ElForm
                          v-if="
                            currentNodeType === '标准模式' ||
                            currentNodeType === 'XNegDL' ||
                            currentNodeType === 'PPUTL' ||
                            currentNodeType === '共享权重'
                          "
                          :model="paramsForm"
                          class="demo-form-inline"
                          style="height: 100%; padding-right: 20px"
                          label-width="100px"
                        >
                          <ElRow>
                            <ElCol class="leftForm" :span="12">
                              <ElFormItem label="模型保存名称">
                                <ElInput
                                  v-model="paramsForm.model_save_name"
                                  style="width: 240px"
                                  placeholder="请输入"
                                  clearable
                                  @blur="appendRandomSuffix"
                                />
                              </ElFormItem>
                              <ElFormItem label="数据选择">
                                <ElSelect v-model="paramsForm.type" placeholder="请选择" size="mini">
                                  <ElOption label="cifar" value="cifar" />
                                  <ElOption label="mnist" value="mnist" />
                                </ElSelect>
                              </ElFormItem>
                              <ElFormItem label="下采样">
                                <ElInputNumber
                                  v-model="paramsForm.subsize_rate"
                                  :min="0.01"
                                  :step="0.01"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                            <ElCol class="rightForm" :span="12">
                              <ElFormItem label="全局迭代">
                                <ElInputNumber
                                  v-model="paramsForm.global_epochs"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="局部迭代">
                                <ElInputNumber
                                  v-model="paramsForm.local_epochs"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="最小设备数量">
                                <ElInputNumber
                                  v-model="paramsForm.min_available_clients"
                                  :min="2"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                          </ElRow>
                          <ElRow>
                            <ElCol class="leftForm" :span="12">
                              <ElFormItem label="模型选择">
                                <ElSelect v-model="paramsForm.model_name" placeholder="请选择" size="mini">
                                  <ElOption label="resnet18" value="resnet18" />
                                  <ElOption label="resnet50" value="resnet50" />
                                  <ElOption label="densenet121" value="densenet121" />
                                  <ElOption label="alexnet" value="alexnet" />
                                  <ElOption label="vgg16" value="vgg16" />
                                  <ElOption label="vgg19" value="vgg19" />
                                  <ElOption label="inception_v3" value="inception_v3" />
                                  <ElOption label="googlenet" value="googlenet" />
                                </ElSelect>
                              </ElFormItem>
                              <ElFormItem label="batch_size">
                                <ElInputNumber
                                  v-model="paramsForm.batch_size"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="dp">
                                <ElSwitch v-model="paramsForm.dp" active-color="#13ce66" inactive-color="#ff4949" />
                              </ElFormItem>
                            </ElCol>
                            <ElCol class="rightForm" :span="12">
                              <ElFormItem label="学习率">
                                <ElInputNumber
                                  v-model="paramsForm.lr"
                                  :min="0.001"
                                  :max="1.0"
                                  :step="0.001"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="momentum">
                                <ElInputNumber
                                  v-model="paramsForm.momentum"
                                  :min="0"
                                  :max="1.0"
                                  :step="0.1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="lambda">
                                <ElInputNumber
                                  v-model="paramsForm.lambda_"
                                  :min="0"
                                  :max="1.0"
                                  :step="0.1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                          </ElRow>
                          <ElDivider>
                            <span style="font-weight: bolder">{{ currentNodeType + '——增量训练' }}</span>
                          </ElDivider>
                          <ElUpload
                            style="padding: 30px"
                            drag
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                            accept="*.pth"
                            :limit="1"
                            :before-upload="beforeUpload"
                          >
                            <ElIcon class="el-icon--upload"><UploadFilled /></ElIcon>
                            <div class="el-upload__text">拖拽或点击上传模型 <em>进行增量训练</em></div>
                            <template #tip>
                              <div class="el-upload__tip">*.pth文件</div>
                            </template>
                          </ElUpload>
                        </ElForm> -->
                        <ElForm
                          v-if="currentNodeType === '差分隐私'"
                          :model="paramsForm"
                          class="demo-form-inline"
                          style="height: 100%; padding-right: 20px"
                          label-width="100px"
                        >
                          <ElFormItem label="C">
                            <ElInputNumber v-model="paramsForm.C" :min="0" size="mini" />
                          </ElFormItem>
                          <ElFormItem label="sigma">
                            <ElInputNumber v-model="paramsForm.sigma" :min="0" :step="0.01" size="mini" />
                          </ElFormItem>
                          <ElFormItem label="q">
                            <ElInputNumber v-model="paramsForm.q" :min="0" :max="1.0" :step="0.1" size="mini" />
                          </ElFormItem>
                          <ElFormItem label="w">
                            <ElInputNumber v-model="paramsForm.w" :step="1" step-strictly size="mini" />
                          </ElFormItem>
                          <!-- <ElRow>
                            <ElCol class="leftForm" :span="12">
                              <ElFormItem label="C">
                                <ElInputNumber v-model="paramsForm.C" :min="0" size="mini" />
                              </ElFormItem>
                              <ElFormItem label="sigma">
                                <ElInputNumber v-model="paramsForm.sigma" :min="0" :step="0.01" size="mini" />
                              </ElFormItem>
                            </ElCol>
                            <ElCol class="rightForm" :span="12">
                              <ElFormItem label="q">
                                <ElInputNumber v-model="paramsForm.q" :min="0" :max="1.0" :step="0.1" size="mini" />
                              </ElFormItem>
                              <ElFormItem label="w">
                                <ElInputNumber v-model="paramsForm.w" :step="1" step-strictly size="mini" />
                              </ElFormItem>
                            </ElCol>
                          </ElRow> -->
                        </ElForm>
                        <ElForm
                          v-else-if="currentNodeType === '同态加密'"
                          :model="paramsForm"
                          class="demo-form-inline"
                          style="height: 100%; padding-right: 20px"
                          label-width="100px"
                        >
                          <ElFormItem label="特征数量">
                            <ElInputNumber
                              v-model="paramsForm.feature_num"
                              :min="1"
                              :step="1"
                              step-strictly
                              size="mini"
                            />
                          </ElFormItem>
                        </ElForm>
                        <!-- 模型选择 -->
                        <ElForm
                          v-else-if="currentNodeType === '自定义模型'"
                          :model="paramsForm"
                          class="demo-form-inline"
                          style="height: 100%; padding-right: 20px"
                          label-width="100px"
                        >
                          <ElRow>
                            <ElCol class="leftForm" :span="12">
                              <ElFormItem label="模型保存名称">
                                <ElInput
                                  v-model="paramsForm.model_save_name"
                                  style="width: 240px"
                                  placeholder="请输入"
                                  clearable
                                  @blur="appendRandomSuffix"
                                />
                              </ElFormItem>
                              <ElFormItem label="全局迭代">
                                <ElInputNumber
                                  v-model="paramsForm.global_epochs"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                            <ElCol class="rightForm" :span="12">
                              <ElFormItem label="最小设备数量">
                                <ElInputNumber
                                  v-model="paramsForm.min_available_clients"
                                  :min="2"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="局部迭代">
                                <ElInputNumber
                                  v-model="paramsForm.local_epochs"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                          </ElRow>
                          <ElDivider>
                            <span style="font-weight: bolder">{{ currentNodeType + '——基本参数' }}</span>
                          </ElDivider>
                          <ElRow>
                            <ElCol class="leftForm" :span="12">
                              <ElFormItem label="batch_size">
                                <ElInputNumber
                                  v-model="paramsForm.batch_size"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="dp">
                                <ElSwitch v-model="paramsForm.dp" active-color="#13ce66" inactive-color="#ff4949" />
                              </ElFormItem>
                            </ElCol>
                            <ElCol class="rightForm" :span="12">
                              <ElFormItem label="学习率">
                                <ElInputNumber
                                  v-model="paramsForm.lr"
                                  :min="0.001"
                                  :max="1.0"
                                  :step="0.001"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="momentum">
                                <ElInputNumber
                                  v-model="paramsForm.momentum"
                                  :min="0"
                                  :max="1.0"
                                  :step="0.1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="lambda">
                                <ElInputNumber
                                  v-model="paramsForm.lambda_"
                                  :min="0"
                                  :max="1.0"
                                  :step="0.1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                          </ElRow>
                          <ElDivider>
                            <span style="font-weight: bolder">{{ currentNodeType + '——模型代码' }}</span>
                          </ElDivider>
                          <ElRow>
                            <ElCol class="button-col" :span="12" style="text-align: center">
                              <ElButton style="background-color: #67c23a" type="success" @click="gotoModelCoding"
                                >在线Coding</ElButton
                              >
                            </ElCol>
                            <ElCol class="button-col" :span="12" style="text-align: center">
                              <ElUpload
                                ref="upload"
                                class="upload-demo"
                                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                                :limit="1"
                                accept="*.pth"
                                :auto-upload="false"
                                :before-upload="beforeUploadModelCode"
                              >
                                <template #trigger>
                                  <ElButton style="background-color: #409eff" type="primary">上传文件</ElButton>
                                </template>
                                <template #tip>
                                  <div class="el-upload__tip text-red">上传模型文件</div>
                                </template>
                              </ElUpload>
                            </ElCol>
                          </ElRow>
                          <ElDivider>
                            <span style="font-weight: bolder">{{ currentNodeType + '——增量训练' }}</span>
                          </ElDivider>
                          <ElUpload
                            style="padding: 30px"
                            drag
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                            accept="*.pth"
                            :limit="1"
                            :before-upload="beforeUpload"
                          >
                            <ElIcon class="el-icon--upload"><UploadFilled /></ElIcon>
                            <div class="el-upload__text">拖拽或点击上传模型 <em>进行增量训练</em></div>
                            <template #tip>
                              <div class="el-upload__tip">*.pth文件</div>
                            </template>
                          </ElUpload>
                        </ElForm>
                        <ElForm
                          v-else-if="modelList.includes(currentNodeType)"
                          :model="paramsForm"
                          class="demo-form-inline"
                          style="height: 100%; padding-right: 20px"
                          label-width="100px"
                        >
                          <ElRow>
                            <ElCol class="leftForm" :span="12">
                              <ElFormItem label="模型保存名称">
                                <ElInput
                                  v-model="paramsForm.model_save_name"
                                  style="width: 240px"
                                  placeholder="请输入"
                                  clearable
                                  @blur="appendRandomSuffix"
                                />
                              </ElFormItem>
                              <ElFormItem label="全局迭代">
                                <ElInputNumber
                                  v-model="paramsForm.global_epochs"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                            <ElCol class="rightForm" :span="12">
                              <ElFormItem label="最小设备数量">
                                <ElInputNumber
                                  v-model="paramsForm.min_available_clients"
                                  :min="2"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="局部迭代">
                                <ElInputNumber
                                  v-model="paramsForm.local_epochs"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                          </ElRow>
                          <ElDivider>
                            <span style="font-weight: bolder">{{ currentNodeType + '——基本参数' }}</span>
                          </ElDivider>
                          <ElRow>
                            <ElCol class="leftForm" :span="12">
                              <ElFormItem label="batch_size">
                                <ElInputNumber
                                  v-model="paramsForm.batch_size"
                                  :min="1"
                                  :step="1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="dp">
                                <ElSwitch v-model="paramsForm.dp" active-color="#13ce66" inactive-color="#ff4949" />
                              </ElFormItem>
                            </ElCol>
                            <ElCol class="rightForm" :span="12">
                              <ElFormItem label="学习率">
                                <ElInputNumber
                                  v-model="paramsForm.lr"
                                  :min="0.001"
                                  :max="1.0"
                                  :step="0.001"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="momentum">
                                <ElInputNumber
                                  v-model="paramsForm.momentum"
                                  :min="0"
                                  :max="1.0"
                                  :step="0.1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                              <ElFormItem label="lambda">
                                <ElInputNumber
                                  v-model="paramsForm.lambda_"
                                  :min="0"
                                  :max="1.0"
                                  :step="0.1"
                                  step-strictly
                                  size="mini"
                                />
                              </ElFormItem>
                            </ElCol>
                          </ElRow>
                          <ElDivider>
                            <span style="font-weight: bolder">{{ currentNodeType + '——增量训练' }}</span>
                          </ElDivider>
                          <ElUpload
                            style="padding: 30px"
                            drag
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                            accept="*.pth"
                            :limit="1"
                            :on-exceed="handleExceed"
                            :before-upload="beforeUpload"
                          >
                            <ElIcon class="el-icon--upload"><UploadFilled /></ElIcon>
                            <div class="el-upload__text">拖拽或点击上传模型 <em>进行增量训练</em></div>
                            <template #tip>
                              <div class="el-upload__tip">*.pth文件</div>
                            </template>
                          </ElUpload>
                        </ElForm>
                        <!-- 数据源 -->
                        <div v-else style="height: 100%">
                          <ElDivider>
                            <span style="font-weight: bolder">{{ currentNodeType + '——基本参数' }}</span>
                          </ElDivider>
                          <ElForm
                            :model="paramsForm"
                            class="demo-form-inline"
                            style="height: 100%; padding-right: 20px"
                            label-width="100px"
                          >
                            <ElRow>
                              <ElCol class="leftForm" :span="12">
                                <ElFormItem label="数据选择">
                                  <ElSelect v-model="paramsForm.type" placeholder="请选择" size="mini">
                                    <ElOption label="cifar" value="cifar" />
                                    <ElOption label="mnist" value="mnist" />
                                  </ElSelect>
                                </ElFormItem>
                              </ElCol>
                              <ElCol class="rightForm" :span="12">
                                <ElFormItem label="下采样">
                                  <ElInputNumber
                                    v-model="paramsForm.subsize_rate"
                                    :min="0.01"
                                    :step="0.01"
                                    step-strictly
                                    size="mini"
                                  />
                                </ElFormItem>
                              </ElCol>
                            </ElRow>
                          </ElForm>
                          <ElDivider>
                            <span style="font-weight: bolder">{{ '选择样本' }}</span>
                          </ElDivider>
                          <!-- <div class="title">参数配置-选择数据源样本</div> -->
                          <div class="model-attr" style="height: calc(100% - 41px)">
                            <ElTabs
                              v-model="SourceActiveName"
                              style="margin-top: 0px; height: 100%; overflow-y: auto"
                              tab-position="left"
                            >
                              <ElTabPane
                                v-for="(item, index) in taskSource"
                                :key="item.owner.id"
                                :label="item.owner.id === mineId ? '自有数据' : item.owner.name"
                                :name="item.owner.id"
                              >
                                <ElTable
                                  v-model:selected="selectedSource[item.owner.id]"
                                  :data="item.data"
                                  :row-key="(record) => record.id"
                                  style="width: 100%"
                                  tooltip-effect="dark"
                                  show-overflow-tooltip
                                  highlight-current-row
                                  stripe
                                  @selectionChange="(selection) => updateSelectedSource(selection, item.owner.id)"
                                >
                                  <ElTableColumn type="selection" width="55" />
                                  <ElTableColumn prop="name" label="样本名称" width="100px" />
                                  <ElTableColumn prop="number" label="样本记录数" width="100px" />
                                  <ElTableColumn prop="description" label="描述" min-width="100px" />
                                </ElTable>
                              </ElTabPane>
                            </ElTabs>
                          </div>
                        </div>
                      </div>
                    </ElMain>
                  </ElContainer>
                </ElAside>
              </template>
              <!-- Tab -->
              <template #bottom-pane>
                <ElTabs
                  v-model="TabActiveName"
                  style="margin-top: 0px; height: 100%; overflow-y: auto"
                  type="border-card"
                >
                  <ElTabPane label="日志" name="logger">
                    <div v-for="(log, index) in logMessages" :key="index" style="color: #888; padding-left: 15px">
                      {{ log }}
                    </div>
                  </ElTabPane>
                  <ElTabPane
                    v-if="completedModelList.length > 0"
                    id="modelResult"
                    ref="modelResult"
                    style="height: 100%"
                    label="模型训练报告"
                    name="result"
                  >
                    <ElTabs
                      v-model="ResultActiveName"
                      style="margin-top: 0px; height: 100%; overflow-y: auto"
                      tab-position="left"
                    >
                      <ElTabPane
                        v-for="(modelNode, index) in completedModelList"
                        :key="index"
                        :label="modelNode.data.type"
                        :name="modelNode.data.type"
                      >
                        <ElTable
                          :data="allTableData[modelNode.data.type] ? allTableData[modelNode.data.type].tableData : []"
                          border
                          style="width: 100%"
                        >
                          <ElTableColumn prop="type" label="类型" width="100" />
                          <ElTableColumn
                            v-for="(iteration, resultIndex) in allTableData[modelNode.data.type]
                              ? allTableData[modelNode.data.type].iterations
                              : []"
                            :key="resultIndex"
                            :prop="iteration"
                            :label="iteration"
                            align="center"
                          />
                        </ElTable>
                        <div :id="'RocChart-' + modelNode.data.type" style="width: 100%; height: 400px" />
                      </ElTabPane>
                    </ElTabs>
                  </ElTabPane>
                </ElTabs>
              </template>
            </VueSplitter>
          </template>
        </VueSplitter>
      </template>
    </VueSplitter>
    <VaModal v-model="isShowWaitModel" size="small" mobile-fullscreen close-button stateful hide-default-actions>
      <h1 class="mb-4 va-h5">等待其它客户端的确认……</h1>
    </VaModal>
    <VaModal
      v-model="isShowSaveModel"
      size="small"
      mobile-fullscreen
      close-button
      stateful
      hide-default-actions
      @close="submitForm"
    >
      <ElForm :model="saveForm" class="demo-form-inline" style="height: 100%" label-width="150px">
        <ElFormItem label="模型保存名称">
          <ElInput v-model="saveForm.name" style="width: 240px" disabled placeholder="Please input" />
        </ElFormItem>
        <ElFormItem label="加密类型">
          <ElInput v-model="saveForm.protect_type" style="width: 240px" disabled placeholder="Please input" />
        </ElFormItem>
        <ElFormItem label="模型类型">
          <ElInput
            v-if="saveForm.model_type === 'self_defined'"
            v-model="saveForm.model_type"
            style="width: 240px"
            placeholder="Please input"
          />
          <ElInput v-else v-model="saveForm.model_type" style="width: 240px" disabled placeholder="Please input" />
        </ElFormItem>
        <ElFormItem label="模型描述（可选）">
          <ElInput v-model="saveForm.description" style="width: 240px" placeholder="Please input" />
        </ElFormItem>
        <ElFormItem style="text-align: right">
          <!-- <ElButton type="primary" @click="submitForm">提交</ElButton> -->
          <ElButton type="primary" plain @click="submitForm">提交</ElButton>
        </ElFormItem>
      </ElForm>
    </VaModal>
  </div>
</template>

<script>
import { $on, $off, $once, $emit } from '@/utils/gogocodeTransfer'
import * as Vue from 'vue'
import ComponentTree from '@/components/ComponentTree.vue'
// import splitPane from 'vue-splitpane'
// import VueSplitter from '@rmp135/vue-splitter'
import VueSplitter from '@/components/vue-splitter/VueSplitter.vue'
import { getTaskModel, getTaskSource, saveTaskModel, ChangeTaskStatus } from '@/api/task'
import FlowChart from '@/utils/FlowChart/index'
import PluginFlowExec from '@/utils/FlowChart/pluginFlowExec'
import waves from '@/directive/waves' // waves directive
import * as echarts from 'echarts'
import { useLoggerStore } from '@/stores/logger' // 假设这是你的Pinia store路径
import { useUserStore } from '../../stores/user-store'
import { markRaw } from 'vue'
import { createModel } from '../../api/model'
import { useRouter } from 'vue-router'

const userStore = useUserStore()

FlowChart.use(PluginFlowExec)

export default {
  components: { ComponentTree, VueSplitter },
  directives: { waves },
  props: {
    sidebarComponentName: String,
  },
  data() {
    return {
      loggerStore: useLoggerStore(),
      router: useRouter(),

      isShowNode: false,
      isShowTab: false,
      currentNodeId: '',
      currentNodeType: '数据源',
      isExecDisable: false,
      isShowWaitModel: false,
      isShowSaveModel: false,
      saveForm: {},

      taskId: this.$route.params.taskId,
      tableData2: [],
      taskSource: [],
      selectedSource: {}, // 用于存储每个owner选中的项
      mineId: userStore.id,
      cooperateList: ['自有数据'],
      SourceActiveName: this.mineId,

      TabActiveName: 'logger',
      ResultActiveName: '',

      encryptionList: ['标准模式', '差分隐私', 'XNegDL', 'PPUTL', '共享权重', '同态加密'],
      modelList: [
        '自定义模型',
        'resnet18',
        'resnet50',
        'densenet121',
        'alexnet',
        'vgg16',
        'vgg19',
        'inception_v3',
        'googlenet',
      ],
      paramsForm: {},
      uploadedFile: null, // 用于存储上传文件的信息
      node: {},
      completedModelList: [],
      allTableData: {}, // 用于存储所有模型类型的表格数据

      // list: null,
      // total: 0,
      // listLoading: true,
      // listQuery: {
      //   page: 1,
      //   limit: 2,
      //   importance: undefined,
      //   title: undefined,
      //   type: undefined,
      //   sort: '-lastTime',
      // },
      RocChart: null,
    }
  },
  computed: {
    node_outerSplitPaneSize() {
      // console.log('1111', this.isShowNode ? 55 : 100)
      return this.isShowNode ? 45 : 100 // 55 100
      // return this.isShowNode ? 30 : 100 // 55 100
    },
    tab_outerSplitPaneSize() {
      // console.log('2222', this.isShowTab ? 60 : 100)
      return this.isShowTab ? 60 : 100 // 60 100
      // return this.isShowTab ? 20 : 100 // 60 100
    },
    logMessages() {
      return this.loggerStore.logs
    },
  },
  watch: {
    currentNodeId(val) {
      // this.paramsForm = FlowChart.getNodeParams(val)
      this.node = FlowChart.getNode(val)
      this.paramsForm = this.node.data.params
      const type = this.node.data.type
      if (type === '标准模式' || type === 'XNegDL' || type === 'PPUTL' || type === '共享权重') {
        // console.log('hhh')
        this.isShowNode = false
      }
      // console.log('当前节点参数', this.node, this.paramsForm)
    },
  },
  created() {
    this.getSimple()
    // this.getList()
    if (this.$route.query.cooperators) {
      const cooperatorsArray = this.$route.query.cooperators.split(',')
      this.cooperateList = ['自有数据', ...cooperatorsArray]
    }
  },
  mounted() {
    FlowChart.setContainer('mainContainer')
    FlowChart.on('selectNode', (id, type) => {
      this.isShowNode = true
      this.currentNodeId = id
      this.currentNodeType = type
    })
    FlowChart.on('modelCompleted', (node) => {
      const nodeType = node.data.type
      this.completedModelList.push(node)
      if (this.completedModelList.length === 1) {
        this.TabActiveName = 'result'
        this.ResultActiveName = nodeType
      }
      // console.log(node.data.result)
      // 转换结果为表格数据并根据模型类型存储
      this.transformResultsToTableData(nodeType, node.data.result)
      // 渲染结果
      this.$nextTick(() => {
        // 渲染图表
        this.initRocChart('RocChart-' + nodeType, node.data.result)
        // 添加大小变化的监听器
        const chartContainer = document.getElementById('RocChart-' + nodeType)
        if (chartContainer) {
          const resizeObserver = new ResizeObserver((entries) => {
            for (const entry of entries) {
              const echartsInstance = echarts.getInstanceByDom(entry.target)
              if (echartsInstance) {
                echartsInstance.resize()
              }
            }
          })
          resizeObserver.observe(chartContainer)

          // 如果需要，可以在组件销毁时停止观察
          $once(this, 'hook:beforeDestroy', () => {
            resizeObserver.unobserve(chartContainer)
          })
        }
      })

      this.saveForm.name = node.data.params.model_save_name
      const protectArray = ['标准模式', '差分隐私', '同态加密', 'XNegDL', 'PPUTL', '共享权重']
      this.saveForm.protect_type = protectArray[node.data.params.choice]
      this.saveForm.model_type = node.data.params.model_name
      this.isShowSaveModel = true
    })
    getTaskModel(this.taskId).then((data) => {
      FlowChart.loadData(data)
      // 添加一个获取selected和设置selected的。
      console.log('数据选择', FlowChart.getDataSelected())
    })

    FlowChart.on('wait_clients', (clients) => {
      this.isShowWaitModel = true
      // console.log(clients)
    })
    FlowChart.on('got_clients', (clients) => {
      this.isShowWaitModel = false
      // console.log(clients)
    })

    this.initializeSelectedSource()
  },
  methods: {
    dragoverHandle(ev) {
      ev.preventDefault()
    },
    dropHandle(ev) {
      FlowChart.addNode({ pageX: ev.pageX, pageY: ev.pageY }, ev.dataTransfer.getData('target'))
    },
    execModel() {
      // saveTaskModel({
      //   id: this.taskId,
      //   data: FlowChart.getModelData(),
      // })
      console.log(FlowChart.getModelData())
      ChangeTaskStatus({
        id: this.taskId,
        status: 'running',
      })
      this.isExecDisable = true
      this.isShowNode = true
      this.isShowTab = true
      // console.log('hhh' + this.isShowNode, this.isShowTab)
      // ************ //
      // 计算出一个ip数组，先算，到时候如果是真实数据就用上
      const IpArray = [] // 用于存放找到的 ip 的数组
      // 遍历 this.selectedSource 来获取每个选中的 ownerId

      IpArray[0] = this.taskSource[0].owner.ip
      for (const ownerId in this.selectedSource) {
        // 在 this.taskSource 中找到对应 ownerId 的 owner 对象
        console.log(ownerId, this.mineId)
        if (ownerId != this.mineId) {
          const owner = this.taskSource.find((o) => o.owner.id == ownerId)
          // 如果找到了对应的 owner 并且它有 ip 属性
          if (owner && owner.owner.ip) {
            // 把这个 ip 加入到 IpArray 数组中
            IpArray.push(owner.owner.ip)
          }
        }
      }
      console.log(IpArray)

      // ************ //
      // 用于存放结果的数组
      // const clientsData = []
      // // 遍历 this.taskSource 来构建 clientsData
      // this.taskSource.forEach((item) => {
      //   const ownerId = item.owner.id
      //   // 检查是否有选中的数据对应这个 ownerId
      //   if (this.selectedSource[ownerId]) {
      //     // 对于每个 ownerId, 找到对应的选中数据
      //     const selectedDataPaths = this.selectedSource[ownerId]
      //       .map((selectedId) => {
      //         // 在 item.data 中找到对应的数据项，并返回其路径
      //         const selectedData = item.data.find((data) => data.id === selectedId)
      //         return selectedData ? selectedData.path : null
      //       })
      //       .filter((path) => path !== null) // 过滤掉未找到的情况

      //     if (selectedDataPaths.length > 0) {
      //       // 如果这个 ownerId 有对应的选中数据，则添加到结果数组中
      //       clientsData.push({
      //         ip: item.owner.ip,
      //         path: selectedDataPaths,
      //       })
      //     }
      //   }
      // })
      // // console.log(clientsData)

      // ['10.132.22.123', '10.82.175.165', '10.83.171.180', '10.132.20.234']
      // const IpArray = ['10.82.175.165', '10.132.22.123', '10.83.171.180', '10.83.102.41']
      // const IpArray = ['loaclhost', '10.132.20.234']
      // // console.log('taskId' + this.taskId)
      FlowChart.runModel(this.loggerStore, IpArray, this.taskId).then(() => {
        this.isExecDisable = false
      })
    },
    async saveData() {
      const modelData = FlowChart.getModelData()
      // // console.log(modelData)
      // // console.log(FlowChart.getCompletedModel())
      // // console.log(modelData)
      const res = await saveTaskModel({
        id: this.taskId,
        data: modelData,
      })
      // console.log(res)
      if (res.code === 200) {
        this.$message.success('模型保存成功')
      } else {
        this.$message.success('模型保存失败')
      }
    },
    getSimple() {
      getTaskSource(this.taskId).then((response) => {
        // console.log(this.$route.query)
        // // console.log(response.data)
        this.taskSource = response.data
        // console.log(this.taskSource)
      })
    },
    handleChange(val) {
      // console.log(val)
    },
    appendRandomSuffix() {
      // 获取已填写的模型保存名称
      let modelName = this.paramsForm.model_save_name.trim()
      console.log(modelName)

      // 如果模型保存名称非空，则追加随机后缀
      if (modelName) {
        modelName += `_${this.generateRandomSuffix()}`
        // 更新模型保存名称
        this.paramsForm.model_save_name = modelName
      }
    },
    generateRandomSuffix() {
      let result = ''
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      const length = 4
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length))
      }
      return result
    },
    submitForm() {
      // 这里可以添加表单验证逻辑，确保表单数据有效

      // 模拟提交逻辑，此处为示例代码，你需要根据实际情况进行修改
      // console.log('提交的表单数据:', {
      //   id: userStore.id,
      //   ...this.saveForm,
      // })
      createModel({
        id: userStore.id,
        ...this.saveForm,
      })

      // 清空表单数据
      this.saveForm.name = ''
      this.saveForm.protect_type = ''
      this.saveForm.model_type = ''
      this.saveForm.description = ''

      // 关闭模态框
      this.isShowSaveModel = false
    },
    initRocChart(id, data) {
      const chartDom = document.getElementById(id)
      this.RocChart = markRaw(echarts.init(chartDom))
      this.RocChart.setOption({
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['Acc', 'Loss'],
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '3%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.acc.map((_, i) => `Epoch ${i + 1}`),
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: 'Acc',
            type: 'line',
            data: data.acc,
            lineStyle: {
              color: 'red', // 红色实线
              width: 2, // 线的宽度
            },
            markPoint: {
              data: [{ type: 'max', name: '最大准确度', symbolSize: 70 }],
              itemStyle: {
                color: 'red', // 红色标记点
              },
            },
          },
          {
            name: 'Loss',
            type: 'line',
            data: data.loss,
            lineStyle: {
              color: 'blue', // 蓝色虚线
              type: 'dashed', // 虚线类型
            },
            markPoint: {
              data: [{ type: 'min', name: '最小损失度', symbolSize: 70 }],
              itemStyle: {
                color: 'blue', // 蓝色标记点
              },
            },
          },
        ],
      })
    },

    transformResultsToTableData(modelType, result) {
      const { acc, loss } = result
      const iterations = acc.map((_, index) => `训练${index + 1}`)
      const accRow = {
        type: 'Acc',
        ...acc.reduce((obj, value, index) => ({ ...obj, [`训练${index + 1}`]: value }), {}),
      }
      const lossRow = {
        type: 'Loss',
        ...loss.reduce((obj, value, index) => ({ ...obj, [`训练${index + 1}`]: value }), {}),
      }
      const tableData = [accRow, lossRow]

      // 将转换后的表格数据存储在allTableData对象中，按模型类型组织
      this.allTableData[modelType] = { tableData, iterations }
    },
    initializeSelectedSource() {
      // this.selectedSource = FlowChart.getDataSelected()
      // console.log('初始化', this.selectedSource)
      this.taskSource.forEach((item) => {
        if (!this.selectedSource[item.owner.id]) {
          this.$set(this.selectedSource, item.owner.id, [])
        }
      })
    },
    // 更新选中状态的方法
    updateSelectedSource(selected, ownerId) {
      // console.log()
      this.selectedSource[ownerId] = selected.map((item) => item.id)
      console.log('select', this.selectedSource)
      FlowChart.setDataSelected(this.selectedSource)
    },
    handleExceed() {
      // 超出限制时的逻辑
    },
    beforeUpload(file) {
      // console.log(file)
      // const isPTH = file.name.endsWith('.pth')
      // if (!isPTH) {
      //   this.$message.error('只能上传.pth文件！')
      //   return false
      // }
      // 用户选择了.pth文件后，直接在这里处理
      this.paramsForm.increment = file.name // 保存文件名
      this.paramsForm.is_increment = true // 设置为true
      console.log('Selected file:', file.name)
      return true
    },
    beforeUploadModelCode(file) {
      return true
    },
    handleUploadSuccess(file) {},
    gotoModelCoding() {
      // console.log(this.router.push)
      // this.router.push({ path: `/coding/${this.taskId}` })
      const url = this.$router.resolve({ path: `/coding/${this.taskId}` }).href
      window.open(url, '_blank')
    },
  },
}
</script>

<style scoped>
.components-container {
  position: relative;
  height: calc(100vh - 72px);
  margin: 0;
}
.tab-container {
  margin: 0px;
}
.leftForm {
  padding: 0 20px;
}
.rightForm {
  padding: 0 0 0 20px;
}
::v-deep .el-tabs__content {
  padding-left: 0px;
}
</style>

<style lang="scss">
.flowChartWrap {
  height: 100%;
  .left {
    border-right: 1px solid #e5e5e5;
    height: 100%;
    .el-tree {
      height: calc(100% - 40px);
      overflow-y: auto;
    }
  }
  .right {
    border-left: 1px solid #e5e5e5;
  }
  .main {
    #mainMenu {
      height: 41px;
      border-bottom: 1px solid #e1e1e1;
      .tool-left {
        float: left;
        .el-button {
          &:first-child {
            margin-left: 10px;
          }
          border: none;
          margin-top: 8px;
        }
      }
      .tool-right {
        float: right;
        .el-button {
          position: relative;
          border: none;
          margin: 3px 0 0 0;
          &:last-child {
            margin-right: 10px;
          }
          background: transparent;
        }
      }
    }
    .mainContainer {
      height: calc(100vh - 72px);
      position: relative;
      // background-color: pink ;
      background-color: rgb(237, 239, 243); /* 背景颜色 */
      background-size: 10px 10px;
      background-image: radial-gradient(circle, rgb(210, 210, 210) 1px, transparent 1px);
      overflow: hidden;
      outline: none !important;
      #mainContainer {
        outline: none !important;
        height: 100%;
        width: 100%;
        position: relative;
      }
    }
  }
  #mainNodeInfo {
    .nodeInfoToolBar {
      border-left: 1px solid #e5e5e5;
      overflow: hidden;
      .tool {
        padding: 8px 0;
        writing-mode: vertical-rl;
        line-height: 32px;
        font-size: 12px;
        border-bottom: 1px solid #ccc;
        cursor: pointer;
        &.acitve {
          background: #eee;
        }
        span {
          margin: 5px 0;
        }
      }
    }
    .title {
      border-bottom: 1px solid #e5e5e5;
      height: 41px;
      font-size: 16px;
      font-weight: bolder;
      // color: #1c9bec;
      line-height: 40px;
      text-align: center;
    }
    // .model-attr {
    //     padding: 0;
    //     .item {
    //     font-size: 12px;
    //     }
    //     .value {
    //     font-size: 12px;
    //     color: #999;
    //     margin-left: 10px;
    //     }
    //     .el-input {
    //     margin-top: 5px;
    //     }
    //     textarea {
    //     margin-top: 5px;
    //     font-family: inherit;
    //     }
    // }
    .node-attr {
      padding: 10px;
      .item {
        font-size: 12px;
      }
      .value {
        font-size: 12px;
        color: #999;
        margin-left: 10px;
      }
    }
    .messageInfo {
      padding: 0px;
      margin: 10px;
      color: #333;
      font-size: 14px;
      .el-card__body {
        padding: 10px;
      }
      p {
        padding: 0;
        margin: 0;
        font-size: 12px;
      }
    }
  }
  .el-aside {
    background: #f8f8f8;
    padding: 0;
    margin: 0;
    .search {
      height: 40px;
      background-color: #f3f3f3;
      padding: 8px 12px;
      box-sizing: border-box;
      border-bottom: 1px solid #e5e5e5;
      .el-input {
        height: 24px;
        .el-input__inner {
          height: 24px;
        }
      }
      .el-input--small .el-input__icon {
        line-height: 24px;
      }
    }
    .el-tree {
      background: transparent;
    }
    .right {
      margin: 0;
    }
  }
  .el-container {
    height: 100%;
  }
  .tabsNav {
    padding: 0;
    .el-tabs--card > .el-tabs__header .el-tabs__nav {
      border-top: 3px solid #01c1de;
      border-radius: 0;
    }
    .el-tabs__item.is-active {
      color: #333 !important;
    }
    .el-tabs__item {
      font-size: 12px;
    }
    .el-tabs__item:focus.is-active.is-focus:not(:active) {
      box-shadow: none !important;
    }
  }
  .el-tree-node__content,
  .el-tree-node {
    min-height: 38px !important;
  }
  .leafNode {
    .node::before {
      content: '';
      position: absolute;
      top: 2px;
      left: 3px;
      border-radius: 2px;
      padding: 13px 2px;
      background: transparent;
    }
    &:hover span.node {
      border: 1px solid #1c9bec !important;
      background: #fff;
      &::before {
        background: #1c9bec;
      }
    }
  }
}

.el-main {
  padding: 0;
}
</style>
